//
//  ReadBookVOrH_VC.m
//  KidReading
//
//  Created by telen on 14/12/23.
//  Copyright (c) 2014年 刘赞黄Telen. All rights reserved.
//

#import "ReadBookVOrH_VC.h"
#import "ConstDefine.h"

NSString* const ReadSource_JR = @"jr";
NSString* const ReadSource_Pep = @"pep";

@interface ASMediaFocusController(Nonrotating)
- (BOOL)shouldAutorotate;
@end

@implementation ASMediaFocusController(Nonrotating)
- (BOOL)shouldAutorotate {
    return NO;
}
@end


@interface ReadBookVOrH_VC ()<UIAlertViewDelegate,ASMediasFocusDelegate>

@end

@implementation ReadBookVOrH_VC
{
    ASMediaFocusManager* mediaFocusManager;
    BOOL statusBarHidden;
}
static ReadBookVOrH_VC* currentReadBookVOrH_VC = nil;
+ (instancetype)currentReadInstance
{
    return currentReadBookVOrH_VC;
}

- (void)dealloc
{
    [[UIApplication sharedApplication] setStatusBarHidden:statusBarHidden];
    self.quizUrl = nil;
    self.bookDict = nil;
    self.bookName = nil;
}

- (void)dealloc_My
{
    [timer invalidate],timer = nil;//必须在pop之前释放，timer对target 强引用
    readView.delegate = nil;
    [NSObject cancelPreviousPerformRequestsWithTarget:readView];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    //
    [[NetDownloadBooks shareSingle] unRegisterDownBooksStatusNotice:self];
    [[WordsDictData shareSingle] unSetGetWordsDelegate:self];
    //
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"quitquiz" object:nil];
    //
    if (currentReadBookVOrH_VC == self)currentReadBookVOrH_VC = nil;
    //
    [DataProcessing shareSingle].hurdleNo = 0;
    [DataProcessing shareSingle].activityId = 0;
    //
    [super dealloc_My];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    currentReadBookVOrH_VC = self;
}

- (void)refreshData{}


- (void)viewDidLoad {
    currentReadBookVOrH_VC = self;
    statusBarHidden = [DataProcessing shareSingle].isStatusHidden;
    //
    [super viewDidLoad];
    //
    if (!self.readSource || self.readSource.length <= 0) {
        self.readSource = ReadSource_JR;
    }
    //
    //
    mediaFocusManager = [[ASMediaFocusManager alloc] init];
    mediaFocusManager.delegate = self;
    mediaFocusManager.fontSize = 22/ratio_w;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        mediaFocusManager.fontSize *= 1.2;
    }
    
    //Pep 语音引擎配置
    eva_model = self.bookDict[@"eva_model"];
    eva_txt = self.bookDict[@"eva_txt"];
    
    //数据处理
    if (self.bookDict) {
        NSArray* pages = [self.bookDict objectForKey:@"pages"];
        nullToNil(pages);
        NSMutableArray* pmarr = [NSMutableArray arrayWithArray:pages];
        if (self.quizUrl && self.quizUrl.length >0){
            NSMutableDictionary* mdic = nil;
            for (NSDictionary* dic in pages) {
                NSNumber* type_ = [dic objectForKey:@"type"];
                nullToNil(type_);
                NSInteger type = [type_ integerValue];
                if (type == BookPageType_pBackCover) {
                    mdic = [NSMutableDictionary dictionaryWithDictionary:dic];
                    [pmarr removeObject:dic];
                }
            }
            if (mdic) {
                [mdic setObject:self.quizUrl forKey:@"name"];
                [mdic setObject:[NSNumber numberWithLongLong:self.quizEdition] forKey:@"quizEdition"];
                [mdic setObject:[NSNumber numberWithInteger:BookPageType_pQuiz] forKey:@"type"];
                [pmarr addObject:mdic];
            }
        }
#ifndef JReaderSDKControl
#ifndef WHY_PJ
        if ([self.readSource isEqualToString:ReadSource_JR]) {
            NSMutableDictionary* mdic = [NSMutableDictionary new];
            [mdic setObject:[NSNumber numberWithInteger:BookPageType_pAccessibility] forKey:@"type"];
            [pmarr addObject:mdic];
        }
#endif
#endif

        self.pagesArr = pmarr;
    }
    //pageid_pageindex 关系
    //页码处理
    pageDisArr = nil;
    pageContentCount = 0;
    menuIndex = 0;
    if (self.pagesArr) {
        NSMutableDictionary* mdict_pii = [NSMutableDictionary new];
        NSMutableArray* pmarr = [NSMutableArray new];
        NSDictionary* fdic = [self.pagesArr objectAtIndex:0];
        for (int i =0; i< self.pagesArr.count; i++) {
            NSDictionary* dic = self.pagesArr[i];
            NSNumber* type_ = [dic objectForKey:@"type"];
            NSString* thumb_name = dic[@"thumb_name"];
            NSString* page_id = dic[@"page_id"];
            nullToNil(type_);
            nullToNil(thumb_name);
            nullToNil(page_id);
            //
            if (page_id) {
                [mdict_pii setObject:@(i) forKey:page_id];
            }
            //
            NSInteger type = [type_ integerValue];
            if(type == BookPageType_pMenu && menuIndex == 0)menuIndex = i;
            if (thumb_name) {
                [pmarr addObject:thumb_name];
            }else{
                switch (type) {
                    case BookPageType_pForeCover:
                    {
                        if(fdic == dic)[pmarr addObject:ReadLocalizedString(@"readercover")];
                        else [pmarr addObject:ReadLocalizedString(@"readertitlepage")];
                    }
                        break;
                        
                    case BookPageType_pBackCover:
                    {
                        [pmarr addObject:ReadLocalizedString(@"readerbackcover")];
                    }
                        break;
                        
                    case BookPageType_pContent:
                    {
                        pageContentCount++;
                        [pmarr addObject:[NSString stringWithFormat:@"%d",(int)pageContentCount]];
                    }
                        break;
                        
                    case BookPageType_pQuiz:
                    {
                        [pmarr addObject:ReadLocalizedString(@"readerquiz")];
                    }
                        break;
                        
                    case BookPageType_pAccessibility:
                    {
                        [pmarr addObject:ReadLocalizedString(@"readerend")];
                    }
                        break;
                    case BookPageType_pMenu:
                    {
                        [pmarr addObject:ReadLocalizedString(@"catalog")];
                    }
                        break;
                    default:
                    {
                        [pmarr addObject:@"..."];
                    }
                        break;
                }
            }
        }
        pageDisArr = pmarr;
        pageId_index_dict = mdict_pii;
    }
    //
    CGRect frame = self.view.frame;
    CGSize size = [self forceToOrientation:self.rotation_to];
    frame.size = size;
    CGRect frameOld = frame;
    
    //ReadView
    NSNumber* bw = [self.bookDict objectForKey:@"w"];
    nullToNil(bw);
    CGFloat book_w = [bw integerValue];
    NSNumber* bh = [self.bookDict objectForKey:@"h"];
    nullToNil(bh);
    CGFloat book_h = [bh integerValue];
    NSString* kok_cl = [self.bookDict objectForKey:@"kok_cl"];
    nullToNil(kok_cl);
    NSAssert(book_h!=0, @"h 必须非零");
    CGFloat ratioWH = frame.size.width/frame.size.height;
    CGFloat ratioBook = book_w/book_h;
    CGFloat scale = 1;
    CGFloat scaleTemp = 1;
    if (ratioWH >=  ratioBook) {
        frame.size.width = frame.size.height*ratioBook;
        scaleTemp = frameOld.size.width/frame.size.width;
    }else{
        frame.size.height = frame.size.width/ratioBook;
        scaleTemp = frameOld.size.height/frame.size.height;
    }
    self.bookRatioWH = frame.size.width/book_w;
    if (scaleTemp >= 0.97 && scaleTemp <= 1.03) {
        scale = scaleTemp;
    }
    if([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone)
    {
        if (scaleTemp >= 0.97 && scaleTemp <= 1.0942) {
            scale = scaleTemp;
        }
    }
//    if ([self isRotationHorizontal:self.rotation_to]) {
        readView = [[ReadView alloc] initWithFrame:frame];
//    }else{
//        readView = [[ReadView alloc] initWithFrame:self.view.frame];
//    }
    //forSDK special
        
    //
    readView.center = CGPointMake(size.width/2, size.height/2);
    [self.view addSubview:readView];
    readView.pageList = self.pagesArr;
    readView.bookid = self.bookid;
    readView.max_scale = [_bookDict[@"max_scale"] floatValue];
    readView.bookOid = self.bookOid;
    readView.bookRatioWH = self.bookRatioWH;
    readView.pageSize = frame.size;
    readView.readSource = self.readSource;
    readView.kokColor = [UIColor colorWithHexString:kok_cl];
    if (!readView.kokColor && [@"###" isEqualToString:kok_cl]) {//卡拉ok 不着色
        readView.kokColor = [[UIColor blueColor] colorWithAlphaComponent:0];
    }
    readView.delegate = self;
    if (_currentIndex >= pageDisArr.count) {
        _currentIndex = 0;
    }
    [readView updateShowPageToIndex:self.currentIndex asynLoad:YES];
    readView.transform = CGAffineTransformMakeScale(scale, scale);
    
    //
    //[self refalshMp3Arr];
    [NSObject msgToTarget:self menthed:@"refalshMp3Arr" refs:nil needReturnValue:NO];
    
    //addTransView
    //[self addTransView];
    [NSObject msgToTarget:self menthed:@"addTransView" refs:nil needReturnValue:NO];
    
    //addWordsView
    //[self addWordsView];
    [NSObject msgToTarget:self menthed:@"addWordsView" refs:nil needReturnValue:NO];
    
    //addMemoView
    //[self addMemoView];
    [NSObject msgToTarget:self menthed:@"addMemoView" refs:nil needReturnValue:NO];
    
    //addFavBtn
    //[self addFavBtn];
    if ([self.readSource isEqualToString:ReadSource_JR]) {
        [NSObject msgToTarget:self menthed:@"addFavBtn" refs:nil needReturnValue:NO];
    }
    
    //addHangMenuForCover
    //[self addHangMenu];
    if ([self.readSource isEqualToString:ReadSource_JR]) {
        [NSObject msgToTarget:self menthed:@"addHangMenu" refs:nil needReturnValue:NO];
        if (self.operMap[@"hwInfo"]) {
            [DataProcessing do_Main:^{
                [NSObject msgToTarget:self menthed:@"addActivityLogo" refs:nil needReturnValue:NO];
            } delay:0.3];
        }
    }
    
    //topBarView PageMapView
    [self addPageMapView];
    [self addTopBarView];
    
    //FloatView
    //[self addFloatView];
    if ([self.readSource isEqualToString:ReadSource_JR]) {
        [NSObject msgToTarget:self menthed:@"addFloatView" refs:nil needReturnValue:NO];
    }
    if ([self.readSource isEqualToString:ReadSource_Pep]) {
        [NSObject msgToTarget:self menthed:@"addFloatView_pep" refs:nil needReturnValue:NO];
    }
    
    //Mutex
    mutex = [TLMutexUIViewDelegate getOneMutexDelegate];
    

    //target
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapSelfView:)];
    tap.delegate = [TLGestureRecognizerDelegate shareSingleTapView_Undo];
    [self.view addGestureRecognizer:tap];
    tap.rippleColor = __BaseBackColor;
    [tap addTapRipple];
    
    //手势翻页
    if (readView) {
        nextSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:readView action:@selector(nextPage)];
        nextSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
        [self.view addGestureRecognizer:nextSwipe];
        
        preSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:readView action:@selector(prevPage)];
        preSwipe.direction = UISwipeGestureRecognizerDirectionRight;
        [self.view addGestureRecognizer:preSwipe];
    }
    
    //
    [self readViewBeganScroll];
    
    [[NetDownloadBooks shareSingle] unRegisterDownBooksStatusNotice:self];
    [[NetDownloadBooks shareSingle] registerDownBooksStatusNotice:self];
    [[WordsDictData shareSingle] unSetGetWordsDelegate:self];
    [[WordsDictData shareSingle] setGetWordsDelegate:self];
    //
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"quitquiz" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickQuitQuiz) name:@"quitquiz" object:nil];
    //
    self.tracPageName = [NSString stringWithFormat:@"Book_%@",self.bookName];
    
    //阅读统计
    [NSObject msgToTarget:self menthed:@"statistical_intopages" refs:nil needReturnValue:NO];
#ifdef JReaderSDKControl
    if ([DataProcessing shareSingle].pageChangedBlock) {
        [DataProcessing shareSingle].pageChangedBlock(self.currentIndex);
    }
#endif
    self.title = RE_main_page;
    //[self statistical_intopages];
    
#if __Debug_TLFileBrowserBook
    //添加长按手势 打开文件夹
    UILongPressGestureRecognizer* longgs=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longpress:)];
    [self.view addGestureRecognizer:longgs];
    longgs.numberOfTouchesRequired = 1;
    longgs.minimumPressDuration=1.0;//定义长按识别时长
}

-(void)longpress:(UILongPressGestureRecognizer*)ges{
    if(ges.state==UIGestureRecognizerStateBegan){
        NSString* bookpath = [DataProcessing bookPathForBookID:self.tb_book.bookId];
        [[TLFileBrowser shareSingle] showBrowserVC_path:bookpath];
    }
#endif
}

- (void)viewDidAppear:(BOOL)animated
{
    if (self.rotation_to != [UIApplication sharedApplication].statusBarOrientation) {
        [self forceOrientationTo:self.rotation_to];
    }
    //
    if(self.isAutoRead)[UIApplication sharedApplication].idleTimerDisabled = YES;//防止锁屏
    //
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    //
    //[self performSelector:@selector(reflashHangMenus) withObject:nil afterDelay:1];
    //[self performSelector:@selector(reflashFavCover) withObject:nil afterDelay:1];
    [DataProcessing do_Main:^{
        [NSObject msgToTarget:self menthed:@"reflashHangMenus" refs:nil needReturnValue:NO];
        [NSObject msgToTarget:self menthed:@"reflashFavCover" refs:nil needReturnValue:NO];
    } delay:1];
    //
    //阅读统计 新的阅读记录
    [NSObject msgToTarget:self menthed:@"statistical_newReading" refs:nil needReturnValue:NO];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [UIApplication sharedApplication].idleTimerDisabled = NO;//关闭防止锁屏
    //
    [super viewWillDisappear:animated];
    //
    //阅读统计 结束阅读记录
    [NSObject msgToTarget:self menthed:@"statistical_endReading" refs:nil needReturnValue:NO];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    readView.isInBackGround = YES;
    //
    //阅读统计 结束阅读记录
    [NSObject msgToTarget:self menthed:@"statistical_endReading" refs:nil needReturnValue:NO];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    readView.isInBackGround = NO;
    [self forceOrientationTo:self.rotation_to];
    //
    //阅读统计 新的阅读记录
    [NSObject msgToTarget:self menthed:@"statistical_newReading" refs:nil needReturnValue:NO];
}

- (void)didTapSelfView:(UITapGestureRecognizer*)tap
{
    NSString* menth = @"didTapSelfView_unShowWordsView";
    NSNumber* unshowWords = [NSObject msgToTarget:self menthed:menth refs:nil needReturnValue:YES];
    if (unshowWords != nil && [self respondsToSelector:NSSelectorFromString(menth)]) {
        return;
    }
    
    menth = @"didTapSelfView_unShowTransView";
    NSNumber* unshowTrans = [NSObject msgToTarget:self menthed:menth refs:nil needReturnValue:YES];
    if (unshowTrans != nil && [self respondsToSelector:NSSelectorFromString(menth)]) {
        return;
    }
    
    menth = @"didTapSelfView_unShowMemoView";
    NSNumber* unshowMemo = [NSObject msgToTarget:self menthed:menth refs:nil needReturnValue:YES];
    if (unshowMemo != nil && [self respondsToSelector:NSSelectorFromString(menth)]) {
        return;
    }
    
     menth = @"isWordsViewWorking";
    NSNumber* wordsViewWorking = [NSObject msgToTarget:self menthed:menth refs:nil needReturnValue:YES];
    if (!wordsViewWorking || ![self respondsToSelector:NSSelectorFromString(menth)])
    {
        if (!topBarView || topBarView.frame.origin.y < 0) {
            [self showTopBarView];
        }else{
            [self hideTopBarView];
        }
    }
}

- (void)tapBack
{
    [[TLSoundPlayer shareSingle] stopAllFiles];
//    if (self.rotation_to == UIInterfaceOrientationLandscapeLeft
//        || self.rotation_to == UIInterfaceOrientationLandscapeRight) {
//        [self setMyRotationToVertical];
//        [self forceOrientationTo:self.rotation_back];
//    }
    UIInterfaceOrientation rotation = self.rotation_back;
//    UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
//    if (statusBarOrientation == UIInterfaceOrientationLandscapeLeft || statusBarOrientation == UIInterfaceOrientationLandscapeRight) {
//        rotation = statusBarOrientation;
//    }
    [self forceOrientationTo:rotation];
    [super tapBack];
    [self dismissViewControllerAnimated:[DataProcessing shareSingle].canWindowRotation completion:^{
        [NSObject msgToTarget:self menthed:@"statistical_tapBack" refs:nil needReturnValue:NO];
        NSDictionary *opDict = @{@"op" : @"clsb",
                                 @"bid" : @(self.bookid).description};
        [self msgTo_menthed:@"uploadPepStatisticsWithOPDict:" refs:@[opDict] needReturnValue:NO];
    }];
    //
}

- (void)clickQuitQuiz
{
    [readView nextPage];
}

- (void)didTapUndo{}

- (void)clickTopMenuBtn
{
    [self pageMapViewDidSelectPageIndex:menuIndex];
    
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"跳到封面"] needReturnValue:NO];
}

- (void)clickTopbarTitleBtn{}

- (void)reflashPageNumber
{
    if (readView.currentPageView.pageType == BookPageType_pContent) {
        pageNumberLabel.text = [NSString stringWithFormat:@"%@/%ld",[pageDisArr objectAtIndex:self.currentIndex],(long)pageContentCount];
    }else{
        pageNumberLabel.text = [NSString stringWithFormat:@"%@",[pageDisArr objectAtIndex:self.currentIndex]];
    }
}

- (void)addTopBarView
{
    UIImage* image = [UIImage imageNamed:@"public_topbar.png"];
    topBarHeight = image.size.height;
    CGFloat topEmpty = 8/ratio_w;
    CGFloat w = width_my;
    CGRect frame = CGRectMake(0, 0, w, topBarHeight);
    //frame.origin.y = -topBarHeight;
    topBarView = [[UIView alloc] initWithFrame:frame];
    topBarView.backgroundColor = [UIColor colorWithPatternImage:image];
    UITapGestureRecognizer* unDoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapUndo)];
    unDoTap.delegate = [TLGestureRecognizerDelegate shareSingleTapView_Undo];
    [topBarView addGestureRecognizer:unDoTap];
    [self.view addSubview:topBarView];
    topBarView.alpha = __barAlpha;
    //
    //
    NSNumber* ret = [self msgTo_menthed:@"addTopBarView_define" refs:@[] needReturnValue:YES];
    if (ret == nil || ([ret isKindOfClass:[NSNumber class]] && ret.boolValue == NO)) {
        //title
        CGFloat x = 90/ratio_w;
        frame = CGRectMake(x*2, 0, w-x*4, topBarHeight-topEmpty);
        UILabel* titleLabel = [[UILabel alloc] initWithFrame:frame];
        titleLabel.text = self.bookName;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont boldSystemFontOfSize:frame.size.height*0.35];
        titleLabel.textColor = [UIColor whiteColor];
        [topBarView addSubview:titleLabel];
        
        //titleBtn
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        frame.size.width = titleLabel.contentSize.width;
        if(frame.size.width < 200/ratio_w)frame.size.width = 200/ratio_w;
        btn.frame = frame;
        btn.center = titleLabel.center;
        [btn addTarget:self action:@selector(clickTopbarTitleBtn) forControlEvents:UIControlEventTouchUpInside];
        [topBarView addSubview:btn];
        
        //pageNumber
        frame = CGRectMake(x*1.5, 0, w-x*2, topBarHeight-topEmpty);
        UILabel* pageLabel = [[UILabel alloc] initWithFrame:frame];
        pageLabel.text = @"0/0";
        pageLabel.font = [UIFont boldSystemFontOfSize:frame.size.height*0.3];
        pageLabel.textColor = [UIColor whiteColor];
        pageLabel.textAlignment = NSTextAlignmentRight;
        [topBarView addSubview:pageLabel];
        pageNumberLabel = pageLabel;
        [self reflashPageNumber];
        
        //TopBar 跳转目录按钮
        NSString* menuName = ReadLocalizedString(@"menuTopBar");
        if(menuIndex==0)menuName = ReadLocalizedString(@"coverTopBar");
        pageNumberLabel.hidden = YES;
        topMenuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [topMenuBtn addTouchScaleTransitions];
        topMenuBtn.titleLabel.font = [UIFont boldSystemFontOfSize:frame.size.height*0.3];
        [topMenuBtn setImage:[UIImage imageNamed:@"public_backlist.png"] forState:UIControlStateNormal];
        [topMenuBtn setImage:[UIImage imageNamed:@"public_backlist.png"] forState:UIControlStateHighlighted];
        [topMenuBtn setTitle:menuName forState:UIControlStateNormal];
        [topBarView addSubview:topMenuBtn];
        topMenuBtn.translatesAutoresizingMaskIntoConstraints = NO;
        [topMenuBtn lyt_centerYWithView:pageNumberLabel];
        [topMenuBtn lyt_alignRightToParentWithMargin:26/ratio_w];
        [topMenuBtn addTarget:self action:@selector(clickTopMenuBtn) forControlEvents:UIControlEventTouchUpInside];
        //    topMenuBtn.layer.borderColor = [UIColor redColor].CGColor;
        //    topMenuBtn.layer.borderWidth = 1;
        
        //AirPlay picker
        MPVolumeView *volumeView = [[MPVolumeView alloc] init];
        volumeView.showsVolumeSlider = NO;
        [topBarView addSubview:volumeView];
        volumeView.translatesAutoresizingMaskIntoConstraints = NO;
        //[volumeView lyt_setSize:CGSizeMake(10, 10)];
        [volumeView lyt_centerYWithView:pageLabel];
        [volumeView lyt_placeLeftOfView:topMenuBtn margin:20];
        
        
#ifdef WHY_PJ
        titleLabel.textColor = __BaseBackColor1;
        pageLabel.textColor = __BaseBackColor1;
#endif
        
        //arrow
        w = 140/ratio_w;
        CGFloat h = topBarHeight-topEmpty;
        UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
        view.backgroundColor = [UIColor clearColor];
        [topBarView addSubview:view];
        //
        TLTapImageView* imgv = [[TLTapImageView alloc] initWithFrame:CGRectMake(0, 0, 44/ratio_w, 44/ratio_w)];
        imgv.normalImage = [UIImage imageNamed:@"public_icon_leftarrow.png"];
        imgv.selectImage = [UIImage imageNamed:@"public_icon_leftarrow.png"];
        imgv.image = imgv.normalImage;
        imgv.center = CGPointMake(40/ratio_w, h/2);
        [view addSubview:imgv];
        //
        UILabel* backLabel = [[UILabel alloc] init];
        backLabel.font = topMenuBtn.titleLabel.font;
        backLabel.text = ReadLocalizedString(@"closeTopBar");
        backLabel.textColor = [UIColor whiteColor];
        [view addSubview:backLabel];
        backLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [backLabel lyt_centerYWithView:imgv];
        [backLabel lyt_alignLeftToParentWithMargin:imgv.size.width*1.2];
        
        //tap
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBack)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [view addGestureRecognizer:tap];
        tap.delegate = [TLGestureRecognizerDelegate shareSingleTapView];
    }
    
    //autoReading
    //[self autoReaderIF];
    [NSObject msgToTarget:self menthed:@"autoReaderIF" refs:nil needReturnValue:NO];
    
    [self showTopBarView];
    if (readView.currentPageView.pageType != BookPageType_pQuiz) {
        [self performSelector:@selector(hideTopBarView) withObject:nil afterDelay:2];
    }else{
        [pageMapView performSelector:@selector(unShow) withObject:nil afterDelay:1];
    }
}

- (void)addPageMapView
{
    if (_needPageMap) {
        pageMapView = [[PageMapView alloc] initWithFrame:CGRectZero];
        [self.view addSubview:pageMapView];
        pageMapView.bookid = self.bookid;
        pageMapView.mapHeigth = 150/ratio_w;
        pageMapView.pagesArr = self.pagesArr;
        pageMapView.pageDisArr = pageDisArr;
        pageMapView.delegate = self;
        pageMapView.currentIndex = _currentIndex;
        [pageMapView flashPageMap];
    }else{
        pageMapView = nil;
    }
}

- (void)showTopBarView
{
    if (!topBarView) {
        [self addTopBarView];
    }

    NSNumber* isWordsViewShowing = [NSObject msgToTarget:self menthed:@"isWordsViewShowing" refs:nil needReturnValue:YES];
    NSNumber* isTransViewShowing = [NSObject msgToTarget:self menthed:@"isTransViewShowing" refs:nil needReturnValue:YES];
    NSNumber* isMemoViewShowing = [NSObject msgToTarget:self menthed:@"isMemoViewShowing" refs:nil needReturnValue:YES];
    if(isWordsViewShowing != nil || isMemoViewShowing != nil || isTransViewShowing != nil || readView.currentPageView.zoomView.zoomScale > 1.01){
        return;
    }

    CGRect frame = topBarView.frame;
    frame.origin.y = 0;
    [UIView animateWithDuration:0.3f animations:^{
        topBarView.frame = frame;
    } completion:^(BOOL finished) {}];
    //
    if (readView.currentPageView.pageType != BookPageType_pQuiz && _needPageMap)[pageMapView show];
    //
    frame = floatframe_topBar;
    id fview = [self msgTo_menthed:@"fview" refs:nil needReturnValue:YES];
    CGRect fframe = CGRectZero;
    id val = [fview valueForKey:@"canBerthRect"];
    if (val)fframe = [val CGRectValue];
    if (!CGRectEqualToRect(frame, fframe)) {
        if(fview)tl_oc_msgToTarget_ref(fview, @"setCanBerthRect:", (void*)(&frame), NO);
        if(fview)[self  msgTo_menthed:@"reflashFloatViewShow" refs:nil needReturnValue:NO];
    }
    //
    id pFView = [self msgTo_menthed:@"pFView" refs:nil needReturnValue:YES];
    fframe = CGRectZero;
    val = [pFView valueForKey:@"canBerthRect"];
    if (val)fframe = [val CGRectValue];
    if (!CGRectEqualToRect(frame, fframe)) {
        if(pFView)tl_oc_msgToTarget_ref(pFView, @"setCanBerthRect:", (void*)(&frame), NO);
        if(pFView)[self  msgTo_menthed:@"reflashFloatViewShow_pep" refs:nil needReturnValue:NO];
    }
    //NSLog(@"floatframe_topBar:%@",NSStringFromCGRect(frame));
}

- (void)hideTopBarView
{

    NSNumber* isWordsViewShowing = [NSObject msgToTarget:self menthed:@"isWordsViewShowing" refs:nil needReturnValue:YES];
    NSNumber* isTransViewShowing = [NSObject msgToTarget:self menthed:@"isTransViewShowing" refs:nil needReturnValue:YES];
    NSNumber* isMemoViewShowing = [NSObject msgToTarget:self menthed:@"isMemoViewShowing" refs:nil needReturnValue:YES];
    if(isWordsViewShowing != nil || isMemoViewShowing != nil || isTransViewShowing != nil){
        return;
    }

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideTopBarView) object:nil];
    if (topBarView) {
        CGRect frame = topBarView.frame;
        frame.origin.y = -topBarHeight;
        [UIView animateWithDuration:0.3f animations:^{
            topBarView.frame = frame;
        } completion:^(BOOL finished) {}];
    }else{
        [self addTopBarView];
    }
    [pageMapView unShow];
    //
    CGRect frame = floatframe_full;
    id fview = [self msgTo_menthed:@"fview" refs:nil needReturnValue:YES];
    CGRect fframe = CGRectZero;
    id val = [fview valueForKey:@"canBerthRect"];
    if (val)fframe = [val CGRectValue];
    if (!CGRectEqualToRect(frame, fframe)) {
        if(fview)tl_oc_msgToTarget_ref(fview, @"setCanBerthRect:", (void*)(&frame), NO);
        if(fview)[self  msgTo_menthed:@"reflashFloatViewShow" refs:nil needReturnValue:NO];
    }
    //
    id pFView = [self msgTo_menthed:@"pFView" refs:nil needReturnValue:YES];
    fframe = CGRectZero;
    val = [pFView valueForKey:@"canBerthRect"];
    if (val)fframe = [val CGRectValue];
    if (!CGRectEqualToRect(frame, fframe)) {
        if(pFView)tl_oc_msgToTarget_ref(pFView, @"setCanBerthRect:", (void*)(&frame), NO);
        //if(pFView)[self  msgTo_menthed:@"reflashFloatViewShow_pep" refs:nil needReturnValue:NO];
    }
    //NSLog(@"floatframe_full:%@",NSStringFromCGRect(frame));
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-
- (void)gotToPageIndex:(NSUInteger)pageindex
{
    if (readView.currentPageView && readView.currentPageView.pageIndex == pageindex) {
        return;
    }
    else if (readView.thePrevPageView && readView.thePrevPageView.pageIndex == pageindex) {
        [readView prevPage];
    }
    else if (readView.theNextPageView && readView.theNextPageView.pageIndex == pageindex) {
        [readView nextPage];
    }
    else{
        [readView updateShowPageToIndex:pageindex];
        [DataProcessing do_Main:^{
            [self readViewDidScrolledTo:readView.currentPageView];
        } delay:0.1];
    }
}

//MARK: ReadView
- (void)readViewDidLoadSuccess_PageView:(PageView *)pageView{}

- (void)readViewBeganScroll
{
    [NSObject msgToTarget:self menthed:@"wordsViewMustUnshow" refs:nil needReturnValue:NO];
    [NSObject msgToTarget:self menthed:@"transViewMustUnshow" refs:nil needReturnValue:NO];
}

- (void)readViewBeganScroll_DragEnd{}

- (void)readViewDidScrolledTo:(PageView *)pageView
{
    self.currentIndex = pageView.pageIndex;
    //
    [self reflashPageNumber];
    pageMapView.currentIndex = _currentIndex, [pageMapView flashCurrentIndex];
    [self hideTopBarView];
    //
    if (readView.currentPageView.pageType == BookPageType_pQuiz) {
        [self showTopBarView];
        [pageMapView unShow];
    }
    //
#ifndef YDYH_PJ
#ifdef WHY_PJ
    [[TLSoundPlayer shareSingle] stopAllFiles];
#endif
#endif
    //
    //[self reflashHangMenus];
    //[self reflashFavCover];
    [NSObject msgToTarget:self menthed:@"reflashHangMenus" refs:nil needReturnValue:NO];
    [NSObject msgToTarget:self menthed:@"reflashFavCover" refs:nil needReturnValue:NO];
    
    //阅读统计
    //[self statistical_intopages];
    [NSObject msgToTarget:self menthed:@"statistical_intopages" refs:nil needReturnValue:NO];
#ifdef JReaderSDKControl
    if ([DataProcessing shareSingle].pageChangedBlock) {
        [DataProcessing shareSingle].pageChangedBlock(self.currentIndex);
    }
#endif
    //阅读统计 更新阅读记录
    [NSObject msgToTarget:self menthed:@"statistical_upDateReading" refs:nil needReturnValue:NO];
    //
//    if (self.isAutoRead) {
//        //[self statistical_play];
//        [NSObject msgToTarget:self menthed:@"statistical_play" refs:nil needReturnValue:NO];
//    }
    //Pep统计某页:(进入某页离开某页)
    NSString *pageStr = readView.currentPageView.pageId;
    if (pageStr) {
        NSDictionary *opDict = [NSDictionary dictionaryWithObjectsAndKeys:@"spg",@"op", @(self.bookid).description,@"bid",readView.currentPageView.pageId,@"pg",nil];
        [self msgTo_menthed:@"pepStatisticsPage:" refs:@[opDict] needReturnValue:NO];
    }
    //
    if (!self.isAutoRead) {
        //记录上次阅读页
        UserInfo* uinfo = [[CacheData shareSingle] getUserLoginInfo];
        [[CacheData shareSingle] updateBook:self.bookid OpenPage:pageView.pageIndex forUid:uinfo.uid];
    }
}

- (void)readViewPageDidZoom:(PageView *)page
{
    if (page == readView.currentPageView) {
        [self hideTopBarView];
    }
}
- (void)readViewDidTapWord:(KoK_RectView *)rectview{}
- (void)readViewDidTapHotArea:(KoK_RectView *)rectView
{
    BOOL isWindowNeedMissNow = NO;
    if (rectView.isHot_Area) {
        //NSLog(@"%@",rectView.action);
        if ([@"openurl" isEqualToString:rectView.action]) {
            if(rectView.source)[[UIApplication sharedApplication] openURL:[NSURL URLWithString:rectView.source]];
            isWindowNeedMissNow = YES;
        }
        else if ([@"playaudio" isEqualToString:rectView.action]) {
            isWindowNeedMissNow = YES;
        }
        else if ([@"playvideo" isEqualToString:rectView.action]) {
            NSString* source = rectView.source;
            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
            BOOL isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
            if (isfileExist) {
                [mediaFocusManager startFocusingView:rectView];
                //Pep统计:视频开始
                NSString *pageStr = readView.currentPageView.pageId;
                NSArray *sourceArr = [rectView.hot_adv_popup valueForKey:@"source"];
                NSDictionary *sourceDcit =sourceArr[0];
                NSArray *uri = [sourceDcit valueForKey:@"uri"];
                NSString *uriStr = [uri[0] lastPathComponent];
                NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                if (pageStr && uriStr && type ) {
                    NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"mov",@"op",@(self.bookid).description,@"bid",pageStr,@"pg",@(1).description,@"opc",uriStr,@"fnm",type,@"ext", nil];
                    if (rectView.src_id) {
                        [opDict setValue:rectView.src_id forKey:@"resid"];
                    }
                    [NSObject msgToTarget:self menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(YES)] needReturnValue:NO];
                }
            }
        }
        else if ([@"viewimg" isEqualToString:rectView.action]) {
            NSString* source = rectView.source;
            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
            BOOL isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
            if (isfileExist) {
                [mediaFocusManager startFocusingView:rectView];
                //Pep统计:图片开始
                NSString *pageStr = readView.currentPageView.pageId;
                NSArray *sourceArr = [rectView.hot_adv_popup valueForKey:@"source"];
                NSDictionary *sourceDcit =sourceArr[0];
                NSArray *uri = [sourceDcit valueForKey:@"uri"];
                NSString *uriStr = [uri[0] lastPathComponent];
                NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                if (pageStr && uriStr && type) {
                    NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"img",@"op",@(self.bookid).description,@"bid", pageStr,@"pg",@(1).description,@"opc" ,uriStr,@"fnm" ,type,@"ext",nil];
                    if (rectView.src_id) {
                        [opDict setValue:rectView.src_id forKey:@"resid"];
                    }
                    [NSObject msgToTarget:self menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(YES)] needReturnValue:NO];
                }
            }
        }
        else if ([@"gotopage" isEqualToString:rectView.action]){
            isWindowNeedMissNow = YES;
            NSString* source = rectView.source;
            if (source) {
                readView.currentPageView.zoomView.zoomScale = readView.currentPageView.zoomView.minimumZoomScale;
                NSInteger indx = source.integerValue;
                [self pageMapViewDidSelectPageIndex:indx];
            }
        }
        //加密数据，事件
        else if ([@"playaudio_crypt" isEqualToString:rectView.action]) {
            isWindowNeedMissNow = YES;
        }
        else if ([@"playvideo_crypt" isEqualToString:rectView.action]) {
            NSString* source = rectView.source;
            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
            BOOL isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
            if (isfileExist) {
                [mediaFocusManager startFocusingView:rectView];
                //Pep统计:视频开始
                NSString *pageStr = readView.currentPageView.pageId;
                NSArray *sourceArr = [rectView.hot_adv_popup valueForKey:@"source"];
                NSDictionary *sourceDcit =sourceArr[0];
                NSArray *uri = [sourceDcit valueForKey:@"uri"];
                NSString *uriStr = [uri[0] lastPathComponent];
                NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                if (pageStr && uriStr && type) {
                    NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"mov",@"op",@(self.bookid).description,@"bid",pageStr,@"pg",@(1).description,@"opc",uriStr,@"fnm",type,@"ext", nil];
                    if (rectView.src_id) {
                        [opDict setValue:rectView.src_id forKey:@"resid"];
                    }
                    [NSObject msgToTarget:self menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(YES)] needReturnValue:NO];
                }
            }
        }
        else if ([@"viewimg_crypt" isEqualToString:rectView.action]) {
            NSString* source = rectView.source;
            NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
            BOOL isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
            if (isfileExist) {
                [mediaFocusManager startFocusingView:rectView];
                //Pep统计:图片开始
                NSString *pageStr = readView.currentPageView.pageId;
                NSArray *sourceArr = [rectView.hot_adv_popup valueForKey:@"source"];
                NSDictionary *sourceDcit =sourceArr[0];
                NSArray *uri = [sourceDcit valueForKey:@"uri"];
                NSString *uriStr = [uri[0] lastPathComponent];
                NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                if (pageStr && uriStr && type) {
                    NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"img",@"op",@(self.bookid).description,@"bid", pageStr,@"pg",@(1).description,@"opc" ,uriStr,@"fnm" ,type,@"ext",nil];
                    if (rectView.src_id) {
                        [opDict setValue:rectView.src_id forKey:@"resid"];
                    }
                    [NSObject msgToTarget:self menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(YES)] needReturnValue:NO];
                }
            }
        }
    }else {
        isWindowNeedMissNow = YES;
    }
    if (isWindowNeedMissNow) {
        [self dismissPopWindow];
    }
}

- (void)popHotArea_adv:(NSDictionary*)pop rectView:(KoK_RectView*)rectView parentVC:(UIViewController*)pVC
{
    ReadPagePopView* popview = [[ReadPagePopView alloc] init];
    popview.popInfo = pop;
    popview.pageView = readView.currentPageView;
    popview.rectview = rectView;
    popview.bookid = self.bookid;
    popview.bookRatioWH = self.bookRatioWH;
    popview.ratio = ratio_w;
    //
    popview.bookOid = self.bookOid;
    popview.pageName = [NSString stringWithFormat:@"%@",[pageDisArr objectAtIndex:self.currentIndex]];
    //
    [popview show:pVC];
}

- (void)dismissPopWindow {
    if (self.popWindow) {
        [self.popWindow dissMissWindowWithOrientation:self.rotation_to];
        self.popWindow = nil;
    }
}

- (void)popRolePlay_HotArea_adv:(NSDictionary*)pop rectView:(KoK_RectView*)rectView
{
    [NSObject msgToClassName:@"PepRolePlayVC" menthed:@"popupRolePlayForm:info:rectView:" refs:@[self,pop,rectView] needReturnValue:NO];
}

- (void)readViewDidTapHotArea_adv:(KoK_RectView *)rectView
{
    if ([rectView.hot_adv_type_local isEqualToString:@"autoscale"]) {
        [self didTapSelfView:nil];
        return;
    }
    
    NSDictionary* pop = rectView.hot_adv_popup;
    //NSString* hottype = rectView.hot_adv_type_local;
    if (pop) {
        NSString* status = pop[@"status"];
        nullToNil(status);
        BOOL status_valid = [status isEqualToString:@"valid"];
        if (status_valid) {
            NSString* ecodetype = pop[@"encode_type"];
            nullToNil(ecodetype);
            BOOL needDecode = [ecodetype isEqualToString:@"normal"];
            NSString* mode = pop[@"mode"];
            nullToNil(mode);
            BOOL mode1_1 = [mode isEqualToString:@"1:1"];
            NSString* is_center = pop[@"is_center"];
            nullToNil(is_center);
            BOOL is_center_x = [is_center boolValue];
            NSArray* source = pop[@"source"];
            nullToNil(source);
            //自取第一个弹出
            
            if (source && source.count > 0) {
                //互斥
                if (rectView.mutex == 1) {
                    //TODO: 互斥 还有其他类型互斥
                    //[[TLSoundPlayer shareSingle] stopAllFiles];
                }
                //
                NSDictionary* dic = source.firstObject;
                NSString* htype = dic[@"type"];
                nullToNil(htype);
                NSArray* uris = dic[@"uri"];
                nullToNil(uris);
                NSString* uri = uris.firstObject;
                if (![uri isKindOfClass:[NSString class]]) {
                    uri = nil;
                    NSLog(@"Error uri is Not NSString");
                }
                //诊断
                if (source.count >1 && ![htype isEqualToString:@"gallery"]) {
                    NSLog(@"Error popup %@",@(source.count));
                }
                
                //链接 http_link
                if ([htype isEqualToString:@"http"] && uri) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:uri]];;
                }
                
                //video
                else if([htype isEqualToString:@"video"] && uri){
                    if (!mode1_1) {
                        UIViewController *windowVC = [[UIViewController alloc] init];
                        self.popWindow = [ReadWindow showReadWindowWithframe:self.view.bounds rootVC:windowVC];
                        rectView.source = uri;
                        if (needDecode) {
                            rectView.action = @"playvideo_crypt";
                        }else{
                            rectView.action = @"playvideo";
                        }
                        [self readViewDidTapHotArea:rectView];
                    }
                }
                
                //audio
                else if([htype isEqualToString:@"audio"] && uri){
                    [self popHotArea_adv:pop rectView:rectView parentVC:nil];
                }
                
                //img
                else if([htype isEqualToString:@"img"] && uri){
                    if (mode1_1 && !is_center_x) {
                        [self popHotArea_adv:pop rectView:rectView parentVC:nil];
                    }else{
                        UIViewController *windowVC = [[UIViewController alloc] init];
                        self.popWindow = [ReadWindow showReadWindowWithframe:self.view.bounds rootVC:windowVC];
                        rectView.source = uri;
                        if (needDecode) {
                            rectView.action = @"viewimg_crypt";
                        }else{
                            rectView.action = @"viewimg";
                        }
                        [self readViewDidTapHotArea:rectView];
                    }
                }
                
                //gallery
                else if([htype isEqualToString:@"gallery"] && uri){
                    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                    BOOL isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
                    if (isfileExist) {
                        UIViewController *windowVC = [[UIViewController alloc] init];
                        self.popWindow = [ReadWindow showReadWindowWithframe:self.view.bounds rootVC:windowVC];
                        NSString *pageStr = readView.currentPageView.pageId;
                        [NSObject msgToTarget:self menthed:@"popGallery:followView:pageId:" refs:@[pop,rectView,pageStr] needReturnValue:NO];
                       //Pep统计: Gallerry开始
                        NSArray *sourceArr = [rectView.hot_adv_popup valueForKey:@"source"];
                        NSDictionary *sourceDcit =sourceArr[0];
                        NSArray *uri = [sourceDcit valueForKey:@"uri"];
                        NSString *uriStr = [uri[0] lastPathComponent];
                        NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                        if (pageStr && uriStr && type) {
                            NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"gallery",@"op",@(self.bookid).description,@"bid",pageStr,@"pg",@(1).description,@"opc",uriStr,@"fnm",type,@"ext", nil];
                            if (rectView.src_id) {
                                [opDict setValue:rectView.src_id forKey:@"resid"];
                            }
                            [NSObject msgToTarget:self menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(YES)] needReturnValue:NO];
                        }
                    }
                }
                
                //h5
                else if([htype isEqualToString:@"h5"] && uri){
                    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                    BOOL isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
                    if (isfileExist) {
                        if (mode1_1 && !is_center_x) {
                            [self popHotArea_adv:pop rectView:rectView parentVC:nil];
                        }else{
                            UIViewController *windowVC = [[UIViewController alloc] init];
                            self.popWindow = [ReadWindow showReadWindowWithframe:self.view.bounds rootVC:windowVC];
                            if (self.popWindow.rootViewController) {
                                [self popHotArea_adv:pop rectView:rectView parentVC:self.popWindow.rootViewController];
                            }else {
                                [self popHotArea_adv:pop rectView:rectView parentVC:self];
                            }
                        }
                    }
                }
                
                //popuptext
                else if ([htype isEqualToString:@"popuptext"] && uri){
                    TransView* transView = [NSObject msgToTarget:self menthed:@"transView" refs:nil needReturnValue:YES];
                    NSNumber* isTransViewWorking = [NSObject msgToTarget:self menthed:@"isTransViewWorking" refs:nil needReturnValue:YES];
                    if (transView) {
                        if (transView.pt_unshowFollowView == rectView){
                            [transView unShow];
                        }else{
                            [transView setText:uri];
                            transView.pt_unshowFollowView = rectView;
                            if (!isTransViewWorking) {
                                [transView show];
                            }
                        }
                    }
                }
                
                //roleplay
                else if([htype isEqualToString:@"roleplay"] && uri && eva_model && eva_txt){
                    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                    NSString* fevamodel =  [DataProcessing bookPathForBookID:self.bookid subDir:eva_model];
                    NSString* fevatxt =  [DataProcessing bookPathForBookID:self.bookid subDir:eva_txt];
                    BOOL isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
                    if (isfileExist)isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:fevamodel];
                    if (isfileExist)isfileExist = [[NSFileManager defaultManager] fileExistsAtPath:fevatxt];
                    if (isfileExist) {
                        NSMutableDictionary* mdict = [NSMutableDictionary dictionaryWithDictionary:pop];
                        [mdict setObject:@(self.bookid) forKey:@"bookid"];
                        [mdict setObject:fevamodel forKey:@"eva_model"];
                        [mdict setObject:fevatxt forKey:@"eva_txt"];
                        if (readView.currentPageView.pageId.length) {
                            [mdict setValue:readView.currentPageView.pageId forKey:@"pageId"];
                        }
                        [self popRolePlay_HotArea_adv:mdict rectView:rectView];
                    }
                }
            }
        }
    }
}

- (void)onManUpdatePagesForZipIndex:(NSNumber*)num
{
    NSInteger zipIndex = [num integerValue];
    zipIndex++;
    [readView updatePagesForZipIndex:zipIndex];
}

- (void)netNotice_DownloadBookFinishedOneZipIndex:(NSInteger)zipIndex bookID:(NSInteger)bookid
{
    if (self.bookid == bookid) {
        [self performSelectorOnMainThread:@selector(onManUpdatePagesForZipIndex:) withObject:[NSNumber numberWithInteger:zipIndex] waitUntilDone:NO];
    }
}

- (void)transViewDidUnshow
{
    StatusButton_2_View* transBtn = [NSObject msgToTarget:self menthed:@"transBtn" refs:nil needReturnValue:YES];
    [transBtn setButtonStatus:NO];
}

- (void)pageMapViewDidSelectPageIndex:(NSInteger)index
{
    [self readViewBeganScroll_DragEnd];
    [self readViewBeganScroll];
    [self gotToPageIndex:index];
}


#pragma mark - ASMediaFocusDelegate
// Returns the view controller in which the focus controller is going to be added.
// This can be any view controller, full screen or not.
- (UIViewController *)parentViewControllerForMediaFocusManager:(ASMediaFocusManager *)mediaFocusManager
{
    if (self.popWindow.rootViewController) {
        return self.popWindow.rootViewController;
    }else {
       return self;
    }
}

- (void)mediaFocusManagerDidDisappear:(ASMediaFocusManager *)focusManager {
    //Pep统计,视频，图片结束
    [self dismissPopWindow];
    
    KoK_RectView *rectView = (KoK_RectView *)focusManager.mediaView;
    NSString *pageStr = readView.currentPageView.pageId;
    
    NSArray *sourceArr = [rectView.hot_adv_popup valueForKey:@"source"];
    NSDictionary *sourceDcit =sourceArr[0];
    NSString *sourceType = [sourceDcit valueForKey:@"type"];
    NSString *opStr = nil;
    if ([sourceType isEqualToString:@"img"]) {
        opStr = @"img";
    }else if ([sourceType isEqualToString:@"video"]) {
        opStr = @"mov";
    }
    NSArray *uri = [sourceDcit valueForKey:@"uri"];
    NSString *uriStr = [uri[0] lastPathComponent];
    NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
    if (pageStr && opStr && uriStr && type) {
         NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:opStr,@"op",@(self.bookid).description,@"bid", pageStr,@"pg",@(1).description,@"opc" ,uriStr,@"fnm" ,type,@"ext",nil];
        if (rectView.src_id) {
            [opDict setValue:rectView.src_id forKey:@"resid"];
        }
        [NSObject msgToTarget:self menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(NO)] needReturnValue:NO];
    }
}

- (void)mediaFocusManagerWillDisappear:(ASMediaFocusManager *)mediaFocusManage
{
    if (mediaFocusManager.addDefinePath) {
        [[NSFileManager defaultManager] removeItemAtPath:mediaFocusManager.addDefinePath error:nil];
        mediaFocusManager.addDefinePath = nil;
    }
}

// Returns the URL where the media (image or video) is stored. The URL may be local (file://) or distant (http://).
- (NSURL *)mediaFocusManager:(ASMediaFocusManager *)mediaFocusManage mediaURLForView:(UIView *)view
{
    KoK_RectView* rectView = (KoK_RectView*)view;
    NSString* source = rectView.source;
    if ([@"playvideo" isEqualToString:rectView.action] && source) {
        NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
        if ([[NSFileManager defaultManager] fileExistsAtPath:file])  {
            return [NSURL fileURLWithPath:file];
        }
    }
    else if ([@"playvideo_crypt" isEqualToString:rectView.action]) {
        NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
        NSString* fileTo = [file stringByDeletingPathExtension];
        fileTo = [fileTo stringByAppendingString:@"-un.mp4"];
        BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
        if(ret){
            mediaFocusManager.addDefinePath = fileTo;
            return [NSURL fileURLWithPath:fileTo];
        }
    }
    return [NSURL URLWithString:@""];
}

// Returns the title for this media view. Return nil if you don't want any title to appear.
- (NSString *)mediaFocusManager:(ASMediaFocusManager *)mediaFocusManager titleForView:(UIView *)view
{
    return @"";
}

- (UIImageView *)mediaFocusManager:(ASMediaFocusManager *)mediaFocusManager imageViewForView:(UIView *)view;
{
    KoK_RectView* rectView = (KoK_RectView*)view;
    NSString* source = rectView.source;
    if (source && [@"viewimg" isEqualToString:rectView.action]) {
        NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
        UIImage* image = [UIImage imageWithContentsOfFile:file];
        UIImageView* igv = [[UIImageView alloc] initWithFrame:rectView.bounds];
        igv.image = image;
        igv.contentMode = UIViewContentModeCenter;
        if (image.size.width > self.view.bounds.size.width || image.size.height > self.view.bounds.size.height) {
            igv.contentMode = UIViewContentModeScaleAspectFit;
        }
        return igv;
    }
    else if (source && [@"viewimg_crypt" isEqualToString:rectView.action]) {
        NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:source];
        NSString* fileTo = [file stringByDeletingPathExtension];
        fileTo = [fileTo stringByAppendingString:@"-un.pj"];
        //BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
        //if(ret){
        //    UIImage* image = [UIImage imageWithContentsOfFile:fileTo];
        NSData* imageData = [[NSData alloc] initWithContentsOfFile:file];
        imageData = [WYCryptDES decryptFileData:imageData key:__WYDEC_Code];
        if(imageData){
            UIImage* image = [UIImage imageWithData:imageData];
            UIImageView* igv = [[UIImageView alloc] initWithFrame:rectView.bounds];
            igv.image = image;
            igv.contentMode = UIViewContentModeCenter;
            if (image.size.width > self.view.bounds.size.width || image.size.height > self.view.bounds.size.height) {
                igv.contentMode = UIViewContentModeScaleAspectFit;
            }
            return igv;
        }
    }
    else if (source &&
        ([@"playvideo" isEqualToString:rectView.action]
         || [@"playvideo_crypt" isEqualToString:rectView.action]
         )) {
        UIImageView* igv = [[UIImageView alloc] initWithFrame:rectView.bounds];
        UIView* v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 8)];
        v.backgroundColor = [UIColor blackColor];
        igv.image = [[v tl_takePicture] imageByApplyingAlpha:0.33];
        return igv;
    }
    return nil;
}


@end
